package com.spring.security.app.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.security.core.support.ServerResponse;
import com.spring.security.core.support.ServerResponseEntity;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Strategy used to handle a failed authentication attempt.
 * <p>
 * Typical behaviour might be to redirect the user to the authentication page (in the case
 * of a form login) to allow them to try again. More sophisticated logic might be
 * implemented depending on the type of the exception. For example, a
 * {@link CredentialsExpiredException} might cause a redirect to a web controller which
 * allowed the user to change their password.
 *
 * @author seabed_moon
 */
@Log4j2
@Component("sunLandAuthenticationFailureHandler")
@AllArgsConstructor
public class SpringAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    private final ObjectMapper objectMapper;

    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     *                  request.
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("LOGIN FAILURE");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ServerResponse failure = ServerResponseEntity.fail(HttpStatus.UNAUTHORIZED.value(), exception.getMessage(), "LOGIN FAILURE");
        response.getWriter().write(objectMapper.writeValueAsString(failure));
    }
}
